package org.dong.samples.web;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.dong.samples.model.PagerModel;
import org.dong.samples.model.Subject;
import org.dong.samples.model.User;
import org.dong.samples.model.vo.MessageVO;
import org.dong.samples.model.vo.SubjectVO;
import org.dong.samples.model.vo.UserVO;
import org.dong.samples.service.TeacherSerivce;
import org.dong.samples.service.UserSubjectHibernateService;
import org.dong.samples.util.ExcelUtils;
import org.dong.samples.util.NowTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
public class UserSubjectController {
	@Autowired
	private LocaleResolver localeResolver;
	
	@Autowired
	private MessageSource messageSource;
	
	@Autowired
	private UserSubjectHibernateService userSubjectHiberanteService;
	
	@Autowired
	private TeacherSerivce teacherSerivce;
	
	@RequestMapping("user")
	public User getUserJDBC(){
		return new User();
	}
	
	@RequestMapping(value = "/changeLocale")
	public String changeLocale(HttpServletRequest request, HttpServletResponse response, String localeType){
		if("en_US".equals(localeType)){
			localeResolver.setLocale(request, response, Locale.US);
		}else if("zh_CN".equals(localeType)){
			localeResolver.setLocale(request, response, Locale.CHINA);
		}
		return "redirect:/users";
	}
	//学生管理列表页面
	@RequestMapping("/users")
	public String users(Model model) throws Exception{
		PagerModel<UserVO> userList = userSubjectHiberanteService.pageFindUser();
		model.addAttribute("edit", messageSource.getMessage("page.index.edit", null, LocaleContextHolder.getLocale()));
		model.addAttribute("userList", userList);
		return "user/userList";
	}
	
	@ResponseBody
	@RequestMapping(value = "/add", method = RequestMethod.POST )
	public MessageVO add(HttpServletRequest request){
		String userId = request.getParameter("userId");
		String userName = request.getParameter("userName");
		String gender = request.getParameter("gender");
		String address = request.getParameter("address");
		String tel = request.getParameter("tel");
		String password = request.getParameter("password");
		String email = request.getParameter("email");
		String birthday = request.getParameter("birthday");
		MessageVO vo = new MessageVO();
		try {
		User user = new User();
		user.setUserId(userId);
		user.setUserName(userName);
		user.setGender(Integer.valueOf(gender));
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
        java.util.Date d = null;    
		d = format.parse(birthday);
        java.sql.Date date = new java.sql.Date(d.getTime());
        user.setBirthday(date);
		user.setAddress(address);
		user.setTel(tel);
		user.setPassword(ExcelUtils.MD5(password));
		System.out.println(ExcelUtils.MD5(password));
		user.setEmail(email);
		if(userSubjectHiberanteService.getUserById(userId)==null){
			userSubjectHiberanteService.createUser(user);
			userSubjectHiberanteService.insertTime(NowTime.getTime(), user.getUserId());
			vo.setMassage("添加成功！");
		}else{
			vo.setMassage("添加失败！");
		}
		} catch (Exception e) {
			e.printStackTrace();
			vo.setMassage("ID过长。。。。");
		}
		return vo;
	}
	
	@ResponseBody
	@RequestMapping(value = "/toEdit", method = RequestMethod.POST)
	public UserVO toEdit(String userId){
		UserVO vo = new UserVO();
		try{
			User user = userSubjectHiberanteService.getUserById(userId);
			BeanUtils.copyProperties(user, vo);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return vo;
	}
	
	@ResponseBody
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public MessageVO editStuent(HttpServletRequest request){
		MessageVO message = new MessageVO();
		User user = new User();
		String userId = request.getParameter("userId");
		String userName = request.getParameter("userName");
		String gender = request.getParameter("gender");
		String address = request.getParameter("address");
		String tel = request.getParameter("tel");
		String email = request.getParameter("email");
		String birthday = request.getParameter("birthday");
		user.setUserId(userId);
		user.setUserName(userName);
		user.setGender(Integer.valueOf(gender));
		user.setAddress(address);
		user.setTel(tel);
		user.setEmail(email);
		try{
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
	        java.util.Date d = null;    
			d = format.parse(birthday);
	        java.sql.Date date = new java.sql.Date(d.getTime());
			User u = userSubjectHiberanteService.getUserById(userId);
			user.setBirthday(date);
			user.setPassword(u.getPassword());
			if(user!=null){
				userSubjectHiberanteService.editUser(user);
				userSubjectHiberanteService.insertTime(NowTime.getTime(), user.getUserId());
				message.setMassage("修改成功！");
			}
		}catch (Exception e) {
			e.printStackTrace();
			message.setMassage("修改失败！");
		}
		return message;
	}
	
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
	public String toDelete(RedirectAttributes redirectAttributes, Model model, @PathVariable String id){
		try {
			userSubjectHiberanteService.deleteUser(id);
			redirectAttributes.addFlashAttribute("message", "删除成功。");
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute("message", "删除失败。");
			e.printStackTrace();
		}
		return "redirect:/users";
	}

	
	//科目管理列表页面
	@RequestMapping("/subjecs")
	public String subjec(Model model, HttpSession session) throws Exception{
//		List<Subject> list = userSubjectHiberanteService.findAllSubject();
		PagerModel<SubjectVO> list = userSubjectHiberanteService.pageFindSubject();
		model.addAttribute("subjectList", list);
		return "subjec/subjecs";
	}
	
	@RequestMapping(value = "/subjecAdd", method = RequestMethod.GET )
	public String toSubjectAdd(Model model){
		Subject list =  new Subject();
		model.addAttribute("subject",list);
		return "subjec/subjecAdd";
	}
	
	@ResponseBody
	@RequestMapping(value = "/subjecAdd", method = RequestMethod.POST )
	public MessageVO  subjecAdd(HttpServletRequest request) throws Exception{
		MessageVO vo = new MessageVO();
		Subject subject = new Subject();
		String subName = request.getParameter("subName");
		String description = request.getParameter("description");
		String testCount = request.getParameter("testCount");
		String totalTime = request.getParameter("totalTime");
		String totalScore = request.getParameter("totalScore");
		String status = request.getParameter("status");
		subject.setSubName(subName);
		subject.setDescription(description);
		subject.setTestCount(Integer.valueOf(testCount));
		subject.setTotalTime(Integer.valueOf(totalTime));
		subject.setTotalScore(Double.parseDouble(totalScore));
		subject.setStatus(Integer.valueOf(status));
		userSubjectHiberanteService.createSubject(subject);
		vo.setMassage("保存成功！");
		return vo;
	}
	
	@ResponseBody
	@RequestMapping(value = "/subjecEdit", method = RequestMethod.POST)
	public SubjectVO subjecEdit(HttpServletRequest request) throws NumberFormatException, Exception{
		String subId = request.getParameter("subId");
		SubjectVO vo = new SubjectVO();
		Subject sub = userSubjectHiberanteService.getSubjectById(Integer.valueOf(subId));
		BeanUtils.copyProperties(sub, vo);
		return vo;
	}
	
	@ResponseBody
	@RequestMapping(value = "/editSubject", method = RequestMethod.POST)
	public MessageVO editSubject(HttpServletRequest request) throws NumberFormatException, Exception{
		String subId = request.getParameter("subId");
		String subName = request.getParameter("subName");
		String description = request.getParameter("description");
		String testCount = request.getParameter("testCount");
		String totalTime = request.getParameter("totalTime");
		String totalScore = request.getParameter("totalScore");
		String status = request.getParameter("status");
		MessageVO vo = new MessageVO();
		Subject subject = new Subject();
		subject.setSubId(Integer.valueOf(subId));
		subject.setSubName(subName);
		subject.setDescription(description);
		subject.setTestCount(Integer.valueOf(testCount));
		subject.setTotalTime(Integer.valueOf(totalTime));
		subject.setTotalScore(Double.parseDouble(totalScore));
		subject.setStatus(Integer.valueOf(status));
		userSubjectHiberanteService.editSubject(subject);
		vo.setMassage("修改成功！");
		return vo;
	}
	
	
	@RequestMapping(value = "/deleteSubject/{subId}", method = RequestMethod.GET)
	public String toDelete(RedirectAttributes redirectAttributes, Model model, @PathVariable Integer subId){
		try {
			Subject s = userSubjectHiberanteService.getSubjectById(subId);
			if(s.getStatus().equals(0)){
				userSubjectHiberanteService.deleteSubject(subId);
				redirectAttributes.addFlashAttribute("message", "删除成功。");
			}else{
				redirectAttributes.addFlashAttribute("message", "该科目正在考试中。");
			}
			
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute("message", "删除失败。");
			e.printStackTrace();
		}
		return "redirect:/subjecs";
	}
	
	@ResponseBody
	@RequestMapping(value = "/editStatus", method = RequestMethod.POST)
	public MessageVO edit(HttpServletRequest request) throws NumberFormatException, Exception{
		MessageVO vo = new MessageVO();
		String subId = request.getParameter("subId");
		String status = request.getParameter("status");
		userSubjectHiberanteService.editStatus(Integer.valueOf(subId), Integer.valueOf(status));
		vo.setMassage("更新状态成功！");
		return vo;
	}
	
	@ResponseBody
	@RequestMapping(value = "/allStudent", method = RequestMethod.POST)
	public Map<String, Object> allStudent(Integer subId) throws Exception{
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("allUser", teacherSerivce.getAllStudent());
		resultMap.put("selectedUser", teacherSerivce.getAllUserBySubject(subId));
		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping(value = "/saveUserSubject", method = RequestMethod.POST)
	public Map<String, Object> saveUserSubject(@RequestParam(name = "subjectStudent[]")String[] subjectStudent, HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", false);
		String subId = request.getParameter("subId");
		List<String> list = new ArrayList<String>();
		for(String student:subjectStudent){
			list.add(student);
		}
		try{
			teacherSerivce.saveSubjectStudent(list, Integer.valueOf(subId));
			resultMap.put("success", true);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}
	
}
